<template>
  <NotLoggedIn v-if="!isLoggedIn" page-content="查看个人内容" />
  <div v-else class="user-page">
    <div class="user">
      <div class="user-info">
        <div class="avatar">
          <div class="avatar-wrapper" @click="openEditProfileModal" v-if="isCurrentUser">
            <img
              :src="userInfo.headshot || defaultAvatar"
              class="user-image"
              style="border: 1px solid rgba(0, 0, 0, 0.08)"
            />
            <div class="edit-overlay">
              <el-icon><Edit /></el-icon>
              <span>编辑</span>
            </div>
          </div>
          <div class="avatar-wrapper" v-else>
            <img
              :src="userInfo.headshot || defaultAvatar"
              class="user-image"
              style="border: 1px solid rgba(0, 0, 0, 0.08)"
            />
          </div>
        </div>
        <div class="info-part">
          <div class="info">
            <div class="basic-info">
              <div class="user-basic">
                <div class="user-nickname">
                  <div class="user-name">{{ userInfo.username || '未知用户' }}</div>
                </div>
                <div class="user-content">
                  <span class="user-redId">账号：{{ userInfo.userID || '未知' }}</span>
                </div>
                <div class="user-content">
                  <span class="user-redId">邮箱：{{ userInfo.email || '未知' }}</span>
                </div>
              </div>
            </div>
            <div class="data-info">
              <div class="user-interactions">
                <div>
                  <span class="count">{{ userStats.following || 0 }}</span>
                  <span class="shows">关注</span>
                </div>
                <div>
                  <span class="count">{{ userStats.followers || 0 }}</span>
                  <span class="shows">粉丝</span>
                </div>
                <div>
                  <span class="count">{{ userStats.articles || 0 }}</span>
                  <span class="shows">文章</span>
                </div>
              </div>
            </div>
          </div>
          <div class="follow" v-if="!isCurrentUser">
            <el-button 
              :type="isFollowing ? 'default' : 'danger'" 
              size="large" 
              round
              @click="toggleFollow"
            >
              {{ isFollowing ? '已关注' : '关注' }}
            </el-button>
          </div>
        </div>
      </div>
    </div>
    <div class="reds-sticky-box user-page-sticky" style="--1ee3a37c: all 0.4s cubic-bezier(0.2, 0, 0.25, 1) 0s">
      <div class="reds-sticky" style="">
        <div class="tertiary center reds-tabs-list" style="padding: 0px 12px">
          <div
              class="reds-tab-item"
              :class="getActiveClass('/note')"
              @click="toNote"
          >
            <span>笔记</span>
          </div>

          <div
              class="reds-tab-item"
              :class="getActiveClass('/collection')"
              @click="toCollection"
          >
            <span>收藏</span>
          </div>

          <div
              class="reds-tab-item"
              :class="getActiveClass('/order')"
              @click="toOrder"
          >
            <span>订单</span>
          </div>

          <div
              class="reds-tab-item"
              :class="getActiveClass('/useraddrs')"
              @click="toAddr"
          >
            <span>地址</span>
          </div>
        </div>
      </div>
    </div>
    <div class="feeds-tab-container">
      <router-view></router-view>
    </div>
    
    <!-- 编辑个人信息弹窗 -->
    <el-dialog
      v-model="showEditProfileModal"
      title="编辑个人信息"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form 
        ref="editFormRef"
        :model="editForm" 
        :rules="rules"
        label-width="80px"
        label-position="top"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" placeholder="请输入用户名" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="editForm.password" 
            type="password" 
            placeholder="请输入密码" 
            show-password
          />
        </el-form-item>
        
        <el-form-item label="头像">
          <div class="avatar-uploader">
            <el-upload
              class="avatar-upload"
              :show-file-list="false"
              :http-request="uploadHeadshot"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="editForm.headshot" :src="editForm.headshot" class="avatar-preview" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditProfileModal = false">取消</el-button>
          <el-button type="primary" @click="updateProfile" :loading="updating">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {ref, onMounted, computed, reactive} from "vue";
import { useRouter, useRoute } from "vue-router";
import { UserProfileApi } from '@/api/new/userProfleApi.js';
import { TravelNoteApi } from '@/api/new/travelNoteApi.js'; // 用于上传头像
import NotLoggedIn from '@/components/NotLoggedIn.vue';
import { Edit, Plus } from '@element-plus/icons-vue';
import { ElMessage, FormInstance, FormRules } from 'element-plus';

import UserUtil from '@/utils/User/User.js';

const router = useRouter()
const route = useRoute()
const isLoggedIn = computed(() => UserUtil.isLogin());
// 默认头像
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';

// 用户信息
const userInfo = ref({});
const userStats = ref({
  following: 0,
  followers: 0,
  articles: 0
});
const userTags = ref([]);
const isFollowing = ref(false);
const isCurrentUser = ref(true);

// 编辑个人信息相关
const showEditProfileModal = ref(false);
const editFormRef = ref<FormInstance>();
const updating = ref(false);
const editForm = reactive({
  userID: '',
  username: '',
  email: '',
  password: '',
  headshot: '',
  bio: ''
});

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
  ]
};

// 打开编辑个人信息弹窗
const openEditProfileModal = () => {
  // 填充表单数据
  editForm.userID = userInfo.value.userID || '';
  editForm.username = userInfo.value.username || '';
  editForm.email = userInfo.value.email || '';
  editForm.password = ''; // 密码不回显
  editForm.headshot = userInfo.value.headshot || '';
  editForm.bio = userInfo.value.bio || '';
  
  showEditProfileModal.value = true;
};

// 上传头像前的验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!');
  }
  return isJPG && isLt2M;
};

// 自定义上传头像方法
const uploadHeadshot = async (options) => {
  try {
    const result = await TravelNoteApi.uploadImage(options.file);
    if (result) {
      editForm.headshot = result;
      ElMessage.success('头像上传成功');
    } else {
      ElMessage.error('头像上传失败');
    }
  } catch (error) {
    console.error('上传头像失败:', error);
    ElMessage.error(`上传失败: ${error.message || '未知错误'}`);
  }
};

// 更新个人信息
const updateProfile = async () => {
  if (!editFormRef.value) return;
  
  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      updating.value = true;
      try {
        // 构建请求参数
        const params = {
          userID: editForm.userID,
          username: editForm.username,
          email: editForm.email,
          headshot: editForm.headshot,
          password: editForm.password
        };
        
        // 调用API更新个人信息
        const result = await UserProfileApi.updateProfile(
          params.userID,
          params.username,
          params.email,
          params.headshot,
          params.password
        );
        
        if (result === '个人资料更新成功') {
          ElMessage.success('个人资料更新成功');
          showEditProfileModal.value = false;
          
          // 刷新用户信息
          fetchUserInfo();
        } else {
          ElMessage.error(result || '更新失败');
        }
      } catch (error) {
        console.error('更新个人信息失败:', error);
        ElMessage.error(`更新失败: ${error.message || '未知错误'}`);
      } finally {
        updating.value = false;
      }
    } else {
      ElMessage.warning('请正确填写表单');
    }
  });
};

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    if(!isLoggedIn.value) {
      return;
    }
    // 获取当前登录用户ID
    const currentUserId = UserUtil.getUserId();
    
    // 获取要查看的用户ID（从路由参数或使用当前用户ID）
    const targetUserId = route.params.userId || currentUserId;
    
    // 判断是否查看自己的主页
    isCurrentUser.value = String(targetUserId) === String(currentUserId);
    
    // 获取用户信息
    const userData = await UserProfileApi.getUserInfo(targetUserId);
    userInfo.value = userData;
    
    // 设置用户标签（示例数据，实际应从API获取）
    userTags.value = ['程序员', '上海', '摄影爱好者'];
    
    // 获取用户统计数据
    try {
      // 获取关注数 - 使用 getFollowingCount API
      const followingResponse = await UserProfileApi.getFollowingCount(targetUserId);
      const followingData = typeof followingResponse === 'string' 
        ? JSON.parse(followingResponse) 
        : followingResponse;
      const followingCount = followingData?.followingCount || 0;
      
      // 获取粉丝数 - 使用 getFollowerCount API
      const followersResponse = await UserProfileApi.getFollowerCount(targetUserId);
      const followersData = typeof followersResponse === 'string' 
        ? JSON.parse(followersResponse) 
        : followersResponse;
      const followersCount = followersData?.followCount || 0;
      
      // 获取文章数 - 使用 getPublishedArticleCount API
      const articlesResponse = await UserProfileApi.getPublishedArticleCount(targetUserId);
      const articlesData = typeof articlesResponse === 'string' 
        ? JSON.parse(articlesResponse) 
        : articlesResponse;
      const articlesCount = articlesData?.publishedArticleCount || 0;
      
      userStats.value = {
        following: followingCount,
        followers: followersCount,
        articles: articlesCount
      };
      
      console.log('用户统计数据:', userStats.value);
    } catch (error) {
      console.error('获取用户统计数据失败:', error);
      userStats.value = {
        following: 0,
        followers: 0,
        articles: 0
      };
    }
    
    // 如果不是查看自己的主页，检查是否已关注
    if (!isCurrentUser.value && currentUserId) {
      try {
        const followStatus = await UserProfileApi.checkFollowStatus(currentUserId, targetUserId);
        isFollowing.value = followStatus.isFollowed;
      } catch (error) {
        console.error('获取关注状态失败:', error);
      }
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
    ElMessage.error(`获取用户信息失败: ${error.message || '未知错误'}`);
  }
};

// 关注/取消关注
const toggleFollow = async () => {
  if (!UserUtil.isLogin()) {
    ElMessage.warning('请先登录');
    return;
  }
  
  try {
    const currentUserId = UserUtil.getUserId();
    const targetUserId = userInfo.value.userID;
    
    if (isFollowing.value) {
      // 取消关注
      await UserProfileApi.unfollowUser(currentUserId, targetUserId);
      isFollowing.value = false;
      ElMessage.success('已取消关注');
    } else {
      // 关注
      await UserProfileApi.followUser(targetUserId, UserUtil.getToken());
      isFollowing.value = true;
      ElMessage.success('关注成功');
    }
    
    // 刷新粉丝数
    const followersCount = await UserProfileApi.getFollowersCount(targetUserId);
    userStats.value.followers = followersCount;
  } catch (error) {
    console.error('关注操作失败:', error);
    ElMessage.error(`操作失败: ${error.message || '未知错误'}`);
  }
};

// 路由跳转方法
const toOrder = () => router.push({ path: "/user/order" })
const toCollection = () => router.push({ path: "/user/collection" })
const toNote = () => router.push({ path: "/user/note" })
const toAddr = () => router.push({ path: "/user/useraddrs" })

// 新增路由匹配逻辑
const getActiveClass = (path: string) => {
  return route.path === "/user"+path ? 'active' : ''
}

// 页面加载时获取用户信息
onMounted(() => {
  fetchUserInfo();
});
</script>

<style lang="less" scoped>
.user-page {
  background: #fff;
  overflow-y: scroll;
  overflow-x: hidden;
  user-select: none;

  .user {
    padding-top: 72px;
    display: flex;
    align-items: center;
    justify-content: center;
    .user-info {
      display: flex;
      justify-content: center;
      padding: 48px 0;

      .avatar {
        .avatar-wrapper {
          text-align: center;
          width: 250.66667px;
          height: 175.46667px;
          position: relative;
          cursor: pointer;
          
          .user-image {
            border-radius: 50%;
            margin: 0 auto;
            width: 70%;
            height: 100%;
            object-fit: cover;
          }
          
          .edit-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.5);
            border-radius: 50%;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            color: white;
            opacity: 0;
            transition: opacity 0.3s;
            width: 70%;
            height: 100%;
            margin: 0 auto;
            
            .el-icon {
              font-size: 24px;
              margin-bottom: 8px;
            }
          }
          
          &:hover .edit-overlay {
            opacity: 1;
          }
        }
      }

      .info-part {
        position: relative;
        width: 100%;

        .info {
          @media screen and (min-width: 1728px) {
            width: 533.33333px;
          }
          margin-left: 32px;
          .basic-info {
            display: flex;
            align-items: center;
            .user-basic {
              width: 100%;
              .user-nickname {
                width: 200px;
                display: flex;
                align-items: center;
                max-width: calc(100% - 96px);
                .user-name {
                  font-weight: 600;
                  font-size: 24px;
                  line-height: 120%;
                  color: #333;
                }
              }
              .user-content {
                width: 100%;
                font-size: 12px;
                line-height: 120%;
                color: rgba(51, 51, 51, 0.6);
                display: flex;
                margin-top: 8px;
                .user-redId {
                  padding-right: 12px;
                }
              }
            }
          }
          .user-desc {
            width: 100%;
            font-size: 14px;
            line-height: 140%;
            color: #333;
            margin-top: 16px;
            white-space: pre-line;
          }
          .user-tags {
            height: 24px;
            margin-top: 16px;
            display: flex;
            align-items: center;
            font-size: 12px;
            color: #333;
            text-align: center;
            font-weight: 400;
            line-height: 120%;
            .tag-item :first-child {
              padding: 3px 6px;
            }
            .tag-item {
              display: flex;
              align-items: center;
              justify-content: center;
              padding: 4px 8px;
              grid-gap: 4px;
              gap: 4px;
              height: 18px;
              border-radius: 41px;
              background: rgba(0, 0, 0, 0.03);
              height: 24px;
              line-height: 24px;
              margin-right: 6px;
              color: rgba(51, 51, 51, 0.6);
            }
          }
          .data-info {
            display: flex;
            align-items: center;
            justify-content: center;
            margin-top: 20px;
            .user-interactions {
              width: 100%;
              display: flex;
              align-items: center;
              .count {
                font-weight: 500;
                font-size: 14px;
                margin-right: 4px;
              }
              .shows {
                color: rgba(51, 51, 51, 0.6);
                font-size: 14px;
                line-height: 120%;
              }
            }
            .user-interactions > div {
              height: 100%;
              display: flex;
              align-items: center;
              justify-content: center;
              text-align: center;
              margin-right: 16px;
            }
          }
        }

        .follow {
          position: absolute;
          margin-left: auto;
          display: block;
          right: 0;
          top: 0;
        }
      }
    }
  }

  .reds-sticky {
    padding: 16px 0;
    z-index: 5 !important;
    background: hsla(0, 0%, 100%, 0.98);
    user-select: none;

    .reds-tabs-list {
      screen and (min-width: 1728px) {
        width: 1445.33333px;
      }
      display: flex;
      flex-wrap: nowrap;
      position: relative;
      font-size: 16px;
      justify-content: center;

      .reds-tab-item {
        padding: 0px 16px;
        margin-right: 0px;

        font-size: 16px;
        display: flex;
        align-items: center;
        box-sizing: border-box;
        height: 40px;
        cursor: pointer;
        color: rgba(51, 51, 51, 0.8);
        white-space: nowrap;
        transition: transform 0.3s cubic-bezier(0.2, 0, 0.25, 1);
        z-index: 1;
      }
      .reds-tab-item.active {
        background-color: rgba(0, 0, 0, 0.03);
        border-radius: 20px;
        font-weight: 600;
        color: rgba(51, 51, 51, 0.8);
      }
    }
  }

  .feeds-tab-container {
    padding-left: 2rem;
  }
}

// 头像上传样式
.avatar-uploader {
  display: flex;
  justify-content: center;
  
  .avatar-upload {
    :deep(.el-upload) {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
      
      &:hover {
        border-color: var(--el-color-primary);
      }
    }
  }
  
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .avatar-preview {
    width: 100px;
    height: 100px;
    display: block;
    object-fit: cover;
  }
}
</style>
